<template >
    <div v-loading="loading"
    element-loading-text="拼命加载中">
        <div   class="van-nav-bar van-hairline--bottom"  >
            <div class="van-nav-bar__content">
                <div class="van-nav-bar__left">
                    <i class="van-icon van-icon-arrow-left van-nav-bar__arrow"><!----></i>
                    <span class="van-nav-bar__text" @click="return2">返回</span></div>
                    <div class="van-nav-bar__title van-ellipsis">{{receiver}}</div></div></div>
                    <br>
                  <div style="height: auto" class="lite-chatbox margin-top-1 margin-bottom-52" id="chat_content">

<div v-for="(item,index) in msgList" :key="index">
         <div class="ieu-chat-description" >{{dataList[index]}}</div>
            <div class="cright cmsg" v-if="username1===item.sender">
              <img class="headIcon1 radius"  :src="pic2" />
              <!-- <span class="namer">{{item.sender}}</span> -->
              <span class="contentr">{{item.content}}</span>
            </div>
            <div class="cleft cmsg" v-else>
              <img class="headIcon radius" :src="pic1" />
              <!-- <span class="namel">{{item.sender}}</span> -->
              <span class="contentl">{{item.content}}</span>
            </div>
          </div>
                  </div>

               <div   class="talk-foot bg-nav vertical-center" v-loading="loading"
    element-loading-text="拼命加载中">
                <i   class="iconfont icon_keyboard margin-left-10 van-icon van-icon-undefined" style="color: rgb(51, 51, 51); font-size: 23px;"><!---->
                <i class="el-icon-s-grid"></i>
                </i>
<div   class="van-cell van-field textarea"><div class="van-cell__value van-cell__value--alone van-field__value">
    <div class="van-field__body">
        <el-input
  type="textarea"
  autosize
  placeholder="请输入内容"
  v-model="text"  style="font-size:15px;color:#B3B3B3; margin-bottom:0px"
  @input="inputMessage()"
  >
</el-input>


     </div></div></div>

      <i  class="iconfont icon_face margin-left-10" color="#333333" size="22">
        <i class="el-icon-circle-plus-outline " style="font-size:25px"></i>

      </i>
         <el-button type="primary" v-if="send" size="normal" class="margin-left-14 send-button" @click="sendMessage()" >发送</el-button>
               </div>
    </div>
</template>
<script>
 import axios from 'axios'
export default {
     data(){
      return{
        dataList:[],
        data:'',
        loading:true,
        receiver:null,
        pic2:'',
        username1:null,
        pic1:null,
        websock: null,
         //发送的消息
        message:'',
        text:'',
        msgList:[],
          //发送按钮
        send:false,
        textareaStyle:'textarea',
        $user:null,
        isLoading: true,
         autosize:{
          maxHeight: 92,
          minHeight: 28 ,
        },
      }
    },

     watch:{
         //监听消息 如果不为空就显示发送按钮
      message: {
        handler(newName, oldName) {
          if(newName!=''){
            this.textareaStyle='textarea-send';
            this.send=true;
          }else{
            this.textareaStyle='textarea';
            this.send=false;
          }
        },
        deep: true,
        immediate: true
      },
     },
     created(){

        console.log(this.$route.query.user)
        this.findUsername()
     this.findMessage()


     },
    methods:{
        // 判断是否超过10分钟
        ifover(time){
            let i=null;
         a:   for(i=this.dataList.length-1;i>=0;i--){
                if(this.dataList[i]){
                    console.log(i)
                    break a;
                }
            }
           if((parseInt(time.split(" ")[0].split("-")[2]) -parseInt(this.dataList[i].split(" ")[0].split("-")[2]) )>0 ){
            this.dataList.push(time)
            this.data=time
           }else if((parseInt(time.split(" ")[1].split(":")[0]) -parseInt(this.dataList[i].split(" ")[1].split(":")[0]) )>0){
            this.dataList.push(time)
             this.data=time
           }else{
            if((parseInt(time.split(" ")[1].split(":")[1])-parseInt(this.dataList[i].split(" ")[1].split(":")[1]))>=5){
                console.log(parseInt(time.split(" ")[1].split(":")[1])-parseInt(this.dataList[i].split(" ")[1].split(":")[1]))
                this.dataList.push(time)
                 this.data=time
            }else{
                this.dataList.push("")
                 this.data=""
            }
           }

        },
        return2(){
            this.$router.push("/message")
        },
        findMessage(){
             let url='http://localhost:8098/findMessageDetail'
            let param={
                id:this.$route.query.user,
                username:localStorage.getItem("token")
            }
            axios.post(url,param).then(resp=>{
                  let result=resp.data
                  console.log(result)
                if(result.code===200){
                    for(let i=0;i<result.data.length;i++){
                        this.dataList.push(result.data[i].createTime)
                    }
                    if(this.username1===result.data[0].sender){
                        this.receiver=result.data[0].receiver
                        this.pic1=result.data[0].rp;
                        this.pic2=result.data[0].sp
                    }else{
                        this.receiver=result.data[0].sender
                        this.pic1=result.data[0].sp;
                        this.pic2=result.data[0].rp
                    }
                    this.msgList=result.data
                     if(this.pic2&&this.pic1){
    this.loading=false;
  }
                }
            })
        },
        findUsername(){
            let param=`token=${localStorage.getItem("token")}`
            let url='http://localhost:8098/iflogin'
            axios.post(url,param).then(resp=>{
                let result=resp.data
                if(result.code===200){
                    this.username1=result.data.name;
                       this.pic1=result.data
                       this.initWebSocket();
                }
            })

        },
        sendMessage(){
            if(!this.text){
                this.$message({
            showClose: true,
          message: '内容不能为空',
          type: 'error'
        });
        return;
            }
            this.message=this.text;
            if(this.websock){
	       		this.websock.close() // 关闭websocket连接
	      	}
              this.initWebSocket() // 初始化weosocket，发起连接
                // 这里使用定时器是为了等待连接后才发送数据，避免错误
	        setTimeout( () => {
	           //添加状态判断，当为OPEN时，前端发送消息给后端
	           if (this.websock.readyState === 1) {
                var aData = new Date();
    console.log(aData) //Wed Aug 21 2019 10:00:58 GMT+0800 (中国标准时间)
    let value =
      aData.getFullYear() + "-" + (aData.getMonth() + 1) + "-" + aData.getDate()+" "+aData.getHours()+":"+aData.getMinutes()+":"+aData.getSeconds();
    console.log(this.value);
    this.ifover(value);
	           		// 把后台需要的参数数据传过去
	               let message = {
                    to:this.receiver,
		               text: this.message,
                       time:this.data
	              }
	         	 //发给后端的数据需要字符串化
	         	 this.websock.send(JSON.stringify(message))
	       		 }
	      	}, 500)
            console.log(this.receiver)
            let param={
                sp:this.pic2,
                sender:this.username1,
                content:this.message
            }
            this.msgList.push(param)
        this.$nextTick(()=>{
      this.toBottom()
    })
        this.text=undefined
        this.send=false;
        },
          toBottom(){
    var height = document.body.clientHeight;
    window.scroll({ top: height , left: 0, behavior: 'smooth' });

  },
        inputMessage:function(){
        console.log('输入框内容变化触发');
        if(this.text){
              this.send=true;
        this.textareaStyle='textarea-send'
        }else{
            this.send=false;
        }

      },
    //   web socket 方法
     initWebSocket(){
         if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
        return false;
      } else{
        let username=this.username1;
        let url = 'ws://localhost:8098/web/'+username
        // 开启一个websocket服务
       this.websock = new WebSocket(url);
         this.websock.onopen = this.websocketonopen
	      this.websock.onmessage = this.websocketonmessage
	      this.websock.onerror = this.websocketonerror
	      this.websock.onclose = this.websocketclose

      }


     },
     //连接成功
	    websocketonopen(){
	      console.log('WebSocket连接成1功')

	    },
     //接收后端返回的数据
	    websocketonmessage(e){
	      let dataJson = JSON.parse(e.data)
          let param={
            sender:dataJson.from,
            content:dataJson.text,
            sp:this.pic1
          }
          this.msgList.push(param)
          this.dataList.push(dataJson.time)
          this.$nextTick(()=>{
      this.toBottom()
    })
	      console.log(dataJson)
	      // 在这里使用后端返回的数据，对数据进行处理渲染

	    },
         //关闭连接
	    websocketclose(e){

	      console.log('断开连接',e)
	    },
    }
}
</script>
<style scoped>
.ieu-chat-description {
    font-size: .32rem;
    color: #919499;
    text-align: center;
    margin-bottom: .42667rem;
}
.ieu-chat-descriptionl {
    font-size: .32rem;
    color: #919499;
    text-align: center;
    margin-left: 50px;
    margin-bottom: .42667rem;
}
.margin-left-10 {
    margin-left: 10px;
}
.van-button::before {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100%;
    height: 100%;
    background-color: #000;
    border: inherit;
    border-color: #000;
    border-radius: inherit;
    transform: translate(-50%,-50%);
    opacity: 0;
    content: ' ';
}
.van-button {
    position: relative;
    display: inline-block;
    box-sizing: border-box;
    margin: 0;
    text-align: center;
    border-radius: 2px;
    cursor: pointer;
    transition: opacity .2s;
    -webkit-appearance: none;
}
.van-button--primary {
    color: #fff;
    background-color: #07c160;
    border: 1px solid #07c160;
}
.van-button--normal {
    font-size: 14px;
}
.margin-left-14 {
    margin-left: 4px;
}
.send-button {
    height: 28px;
    width: 52px;
    line-height: 26px;
    padding: 0;
}
.van-cell::after {
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 16px;
    bottom: 0;
    left: 16px;
    border-bottom: 1px solid #ebedf0;
    transform: scaleY(.5);
}
textarea {
    writing-mode: horizontal-tb !important;
        cursor: text;
    white-space: pre-wrap;
        column-count: initial !important;
    text-transform: none;
    text-indent: 0px;
    text-shadow: none;
    cursor: text;
    white-space: pre-wrap;
    overflow-wrap: break-word;
    font: inherit;
    height: 32px!important;
}

.van-field__body {
    display: flex;
    -webkit-box-align: center;
    align-items: center;
}
.van-cell__value {
        -webkit-box-flex: 1;
    flex: 1;
    position: relative;
    vertical-align: middle;
    word-wrap: break-word;
}
.van-field__value {
    overflow: visible;
}
.van-cell__value--alone {
    color: #323233;
    text-align: left;
}
.textarea {
    /* width: 200px; */
    width: 68%;
    margin-left: 5px;
}
.van-cell {
    position: relative;
    display: flex;
    box-sizing: border-box;
    overflow: hidden;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
    padding: 0;
}

.van-icon:before {
    display: inline-block;
}
.van-icon {
    position: relative;
    display: inline-block;
    font: normal normal normal 14px/1 vant-icon;
    text-rendering: auto;
}
.margin-left-10 {
    margin-left: 10px;
}
.iconfont {
    font-family: "iconfont" !important;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
}
.vertical-center {
    display: flex;
    align-items: center;
}
.bg-nav {
    background: #EDEDED;
}
.talk-foot {
    border: 2px;
    width: 100%;
    height: 46px;
    z-index: 5;
    position: fixed;
    bottom: 0;
    left: 0;
}
.headIcon1 {
    width: 35px;
    height: 35px;
    top: 0px;
    position: absolute;
    right: 0;
}
.contentr {
    font-weight: normal;
    word-break: break-all;
    word-wrap: break-word;
    text-align: left;
    position: relative;
    display: inline-block;
    font-size: 15px;
    padding: 10px 15px;
    line-height: 20px;
    min-width: 9px;
    min-height: 18px;
    margin: 0 40px 0 0;
    border-radius: 5px 5px 5px 5px;
    /* color: white; */
    /* border: 1px solid #78cdf8; */
    /* background: -webkit-linear-gradient(70deg, #3FD1E1 0%, #44D7CD 100%); */
    background: #6ae6ea;
    /* background: rgb(9,187,7); */
    /* -webkit-box-shadow: 5px 5px 15px 0 rgb(102 102 102 / 15%); */
    /* box-shadow: 5px 5px 15px 0 rgb(102 102 102 / 15%); */
}
.namer {
        color: #8b8b8b;
    font-size: 12px;
    display: block;
    line-height: 18px;
    margin: -18px 42px 2px 0;
}
.contentl {
        font-weight: normal;
    word-break: break-all;
    word-wrap: break-word;
    text-align: left;
    position: relative;
    display: inline-block;
    font-size: 15px;
    padding: 10px 15px;
    line-height: 20px;
    min-width: 9px;
    min-height: 18px;
    margin: 0 0 0 40px;
    border-radius: 5px 5px 5px 5px;
    color: rgb(255, 255, 255);
    border: 1px solid rgba(0, 0, 0, 0.05);
    background: #000000;
    /* -webkit-box-shadow: 5px 5px 15px 0 rgb(102 102 102 / 10%); */
    /* box-shadow: 5px 5px 15px 0 rgb(102 102 102 / 10%); */
}
.namel {
        color: #8b8b8b;
    font-size: 12px;
    display: block;
    line-height: 18px;
    margin: -18px 0px 2px 48px;
}
.radius {
    border-radius: 5px;
}
.headIcon {
        width: 35px;
    height: 35px;
    top: 0px;
    position: absolute;
    left: 0;
}
.cright {
    text-align: right;
    margin-left: 64px;
}
.cmsg {
    white-space: pre-wrap;
    position: relative;
    margin: 10px 15px;
    min-height: 50px;
    border: 0;
}
.cleft {
    text-align: left;
    margin-right: 64px;
}
.margin-bottom-52 {
    margin-bottom: 52px;
}
.lite-chatbox {
    font-family: Helvetica, "PingFang SC", "Microsoft YaHei", sans-serif;
    padding: 0px;
    font-size: 18px;
    width: 100%;
    position: relative;
    overflow-y: auto;
    overflow-x: hidden;
    height: calc(100vh - 100px);
}
.van-hairline--bottom::after {
    border-bottom-width: 1px;
}

[class*=van-hairline]::after {
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    top: -50%;
    right: -50%;
    bottom: -50%;
    left: -50%;
    border: 0 solid #ebedf0;
    transform: scale(.5);
}
.van-ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.van-nav-bar__title {
    max-width: 60%;
    margin: 0 auto;
    color: #323233;
    font-weight: 500;
    font-size: 16px;
}
.van-nav-bar__text {
    color: #1989fa;
}
.van-nav-bar__arrow {
    margin-right: 4px;
    font-size: 16px;
}
.van-icon {
    position: relative;
    display: inline-block;
    font: normal normal normal 14px/1 vant-icon;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    color: #1989fa;
}
.van-nav-bar__left {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    padding: 0 16px;
    font-size: 14px;
    cursor: pointer;
    left: 0;
}
.van-nav-bar__content {
    position: relative;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    height: 46px;
}
.van-nav-bar {
    margin: -5px;
    position: relative;
    z-index: 1;
    line-height: 22px;
    text-align: center;
    background-color: #fff;
    user-select: none;
}
</style>
